package com.lxmes.gs.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.lxmes.common.utils.DateUtils;
import com.lxmes.common.utils.SecurityUtils;
import com.lxmes.gs.domain.*;
import com.lxmes.gs.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lxmes.common.utils.StringUtils;
import com.lxmes.common.utils.bean.BeanValidators;
import com.lxmes.common.exception.ServiceException;
import javax.validation.Validator;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxmes.gs.mapper.ProjectChangesMapper;
import org.springframework.transaction.annotation.Transactional;

/**
 * 项目管控Service业务层处理
 * 
 * @author wdf
 * @date 2023-04-24
 */
@Service
public class ProjectChangesServiceImpl extends ServiceImpl<ProjectChangesMapper,ProjectChanges> implements IProjectChangesService{
    
    @Autowired
    private ProjectChangesMapper projectChangesMapper;
    @Autowired
    protected Validator validator;
    @Autowired
    private ICreateTaskService createTaskService;
    @Autowired
    private IProjectStatisticsService projectStatisticsService;
    
    @Autowired
    private IWorkingHoursStandardService workingHoursStandardService;

    @Autowired
    private IProjectApprovalService projectApprovalService;
    /**
     * 查询项目管控
     * 
     * @param id 项目管控主键
     * @return 项目管控
     */
    @Override
    public ProjectChanges selectProjectChangesById(Long id){
        return projectChangesMapper.selectById(id);
    }

    /**
     * 查询项目管控列表
     * 
     * @param projectChanges 项目管控
     * @return 项目管控
     */
    @Override
    public List<ProjectChanges> selectProjectChangesList(ProjectChanges projectChanges){
        return projectChangesMapper.selectList(Wrappers.lambdaQuery(projectChanges));
    }

    /**
     * 新增项目管控
     * 
     * @param projectChanges 项目管控
     * @return 结果
     */
    @Override
    public int insertProjectChanges(ProjectChanges projectChanges){
        return projectChangesMapper.insert(projectChanges);
    }

    /**
     * 修改项目管控
     * 
     * @param projectChanges 项目管控
     * @return 结果
     */
    @Override
    public int updateProjectChanges(ProjectChanges projectChanges){
        return projectChangesMapper.updateById(projectChanges);
    }

    /**
     * 批量删除项目管控
     * 
     * @param ids 需要删除的项目管控主键
     * @return 结果
     */
    @Override
    public int deleteProjectChangesByIds(Long[] ids){
        return projectChangesMapper.deleteProjectChangesByIds(ids);
    }

    /**
     * 删除项目管控信息
     * 
     * @param id 项目管控主键
     * @return 结果
     */
    @Override
    public int deleteProjectChangesById(Long id){
        return projectChangesMapper.deleteById(id);
    }
    @Override
    public String imporIteminfo(List<ProjectChanges> projectChangesList, boolean updateSupport) {
        if (StringUtils.isNull(projectChangesList) || projectChangesList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (ProjectChanges projectChanges : projectChangesList)
        {
            try
            {
                BeanValidators.validateWithException(validator, projectChanges);
                this.insertProjectChanges(projectChanges);
                successNum++;
                successMsg.append("<br/>" + successNum + "数据导入成功");
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/> 数据导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int auditProjectChangesByIds(Long[] ids) {
        List<ProjectChanges> projectChangesList = baseMapper.selectBatchIds(Arrays.asList(ids));
        if (projectChangesList.stream().anyMatch(i -> StrUtil.equals(i.getAudit(), "1"))) {
            throw new ServiceException("存在已审核数据,审核下发失败");
        }
        for (ProjectChanges projectChanges : projectChangesList) {
            projectChanges.setAudit("1");
            projectChanges.setReceiveTime(new Date());
            projectChanges.setReceiver(SecurityUtils.getUsername());
            baseMapper.updateById(projectChanges);
            
            CreateTask createTask = new CreateTask();
            createTask.setProjectCode(projectChanges.getApprovalCode());
            createTask.setProjectName(projectChanges.getApprovalName());
            createTask.setCreateTime(new Date());
            createTask.setStartTime(projectChanges.getStartTime());
            createTask.setEndTime(projectChanges.getEndTime());
            WorkingHoursStandard workingHoursStandard = workingHoursStandardService.getOne(Wrappers.lambdaQuery(WorkingHoursStandard.class).eq(WorkingHoursStandard::getProjectCode, createTask.getProjectCode()));
            createTask.setPlannedWorkingHours(workingHoursStandard.getPlannedWorkingHours());
            //翁佃峰TODO 2023/4/25 9:38  ??预算费用是否是项目立项的总预算
            ProjectApproval projectApproval = projectApprovalService.getOne(Wrappers.lambdaQuery(ProjectApproval.class).eq(ProjectApproval::getApprovalCode, createTask.getProjectCode()));
            createTask.setBudget(projectApproval.getProjectTotalBudget());
            createTask.setAudit("0");
            createTaskService.insertCreateTask(createTask);
            ProjectStatistics projectStatistics = projectStatisticsService.getOne(Wrappers.lambdaQuery(ProjectStatistics.class).eq(ProjectStatistics::getApprovalCode, projectChanges.getApprovalCode()));
            projectStatistics.setChangeType(projectChanges.getChangeType());
            projectStatistics.setChangeDescription(projectChanges.getChangeDescription());
            projectStatistics.setChangeTime(projectChanges.getChangeTime());
            projectStatisticsService.insertProjectStatistics(projectStatistics);
        }
        return 1;
    }
}
